import { onMounted, onUnmounted, ref } from 'vue';
import type { Ref } from 'vue';

const useContextMenu = (containerRef: Ref<HTMLElement | undefined>) => {
  const showMenu = ref(false);
  const x = ref(0);
  const y = ref(0);

  // 右键点击事件处理
  const handleContextMenu = (e: MouseEvent) => {
    e.preventDefault(); // 阻止默认事件
    e.stopPropagation(); // 阻止冒泡

    // 边界问题

    showMenu.value = true;
    x.value = e.clientX;
    y.value = e.clientY;
  };

  const closeMenu = () => {
    showMenu.value = false;
  };

  onMounted(() => {
    const div = containerRef.value as HTMLElement;
    div.addEventListener('contextmenu', handleContextMenu);
    // 第三个参数设置为 true 表示事件句柄在捕获阶段执行
    window.addEventListener('click', closeMenu, true);
    // 处理 window 的 contextmenu 事件，用来关闭之前打开的菜单
    window.addEventListener('contextmenu', closeMenu, true);
  });
  onUnmounted(() => {
    const div = containerRef.value as HTMLElement;
    div.removeEventListener('contextmenu', handleContextMenu);
    window.removeEventListener('click', closeMenu, true);
    window.removeEventListener('contextmenu', closeMenu, true);
  });
  return {
    showMenu,
    x,
    y,
  };
};

export default useContextMenu;
